package com.tencent.wepay.handler.xml;

import java.util.HashMap;
import java.util.Map;

import com.tencent.wepay.protocol.domain.XStreamDomain;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
/**
 * xml处理
 * @author sunzhenyu
 */
public class XStreamHandler {
	private final static XppDriver nameDriver=new XppDriver(new XmlFriendlyNameCoder("-_", "_"));
	@SuppressWarnings("rawtypes")
	private final static Map<Class,XStream> streamCache=new HashMap<Class,XStream>(){
	private static final long serialVersionUID = 7564495215220775381L;
		@Override
		public XStream get(Object key) {
			if(!this.containsKey(key)){
				XStream xStream=new XStream(nameDriver);
				xStream.processAnnotations((Class)key);
				xStream.ignoreUnknownElements();
				this.put((Class)key, xStream);
				return xStream;
			}
			return super.get(key);
		}
	};
	/**
	 * 对象转xml
	 * @param bean
	 * @return
	 */
	public static String toXML(XStreamDomain bean){
		XStream xStream=streamCache.get(bean.getClass());
		return xStream.toXML(bean);
	}
	/**
	 * xml转对象
	 * @param clz 对象class
	 * @param xml xml字符串
	 * @return
	 */
	public static <T> T toBean(Class<T> clz,String xml){
		XStream xStream=streamCache.get(clz);
		@SuppressWarnings("unchecked")
		T bean=(T) xStream.fromXML(xml);
		return bean;
	}
}
